/**
 * http管理器
 * Name = httpManager
 * DateTime = Sun Jan 16 2022 20:39:58 GMT+0800 (中国标准时间)
 * Author = Created by zhj9922
 * FileBasename = httpManager.ts
 * gitee： https://gitee.com/coyeking
 */
import { sys,game,director } from "cc";
import { config } from "../config";
import { uiManager } from "./uiManager";
import { util } from "../utils/Util";
import { constant } from "../define/constant";

let timeout = 8000;//超时请求
export class httpManager {
    /**
     * get请求
     * @param url 
     * @param data 
     * @param succCallBack 
     * @param errCallBack 
     */
    public static get(url: string, data?: any, succCallBack?: (response?: any) => void, errCallBack?: (response?: any) => void) {
        if (data == null) {
            data = {};
        }
        data.token = sys.localStorage.getItem(constant.LOCAL_STORAGE.USER_TOKEN);

        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                if (rsp.code == 0) {
                    errCallBack && errCallBack(rsp);
                    return;
                }
                if (rsp.code == 1) {
                    succCallBack && succCallBack(rsp);
                    return;
                }
            } else if (xhr.readyState === 4 && xhr.status == 401) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                uiManager.showAlert(rsp.msg,{success:()=>{
                    sys.localStorage.removeItem(constant.LOCAL_STORAGE.USER_TOKEN)
                    director.loadScene("loginscence");
                },fail:()=>{
                    game.end()
                }});
                errCallBack && errCallBack(rsp.msg);
            } else {
                // let respone = xhr.responseText;
                // let rsp = JSON.parse(respone);
                // createMsgBox(`${rsp.msg},错误码：${rsp.code}`);
                // errCallBack(rsp.msg);
            }
        };

        let httpurl = `${config.baseUrl}${url}?${util.queryParams(data)}`;
        xhr.withCredentials = false;
        xhr.open('GET', httpurl, true);
        xhr.timeout = timeout;

        xhr.ontimeout = function (e) {
            errCallBack && errCallBack('请求超时！');
            uiManager.showAlert('请求超时！');
        };
        xhr.onerror = function () {
            errCallBack && errCallBack('网络错误！');
            uiManager.showAlert('请求超时！');
        };
        xhr.send();
    };

    public static post(url: string, data?: any, succCallBack?: (response?: any) => void, errCallBack?: (response?: any) => void) {
        if (data == null) {
            data = {};
        }
        data.token = sys.localStorage.getItem(constant.LOCAL_STORAGE.USER_TOKEN);
    
        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status == 200) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                if (rsp.code == 0){
                    errCallBack && errCallBack(rsp);
                    return;
                }
                if (rsp.code == 1){
                    succCallBack && succCallBack(rsp);
                    return;
                }
            } else if (xhr.readyState === 4 && xhr.status == 401) {
                let respone = xhr.responseText;
                let rsp = JSON.parse(respone);
                uiManager.showAlert(rsp.msg,{success:()=>{
                    // 更新token
                    sys.localStorage.removeItem(constant.LOCAL_STORAGE.USER_TOKEN)
                    director.loadScene("loginscence");
                },fail:()=>{
                    game.end()
                }});
                errCallBack && errCallBack(rsp.msg);
            }else{
                // let respone = xhr.responseText;
                // let rsp = JSON.parse(respone);
                // createMsgBox(`${rsp.msg},错误码：${rsp.code}`);
                // errCallBack(rsp.msg);
            }
        };
        
        let httpurl = config.baseUrl + url;
        xhr.withCredentials = false;
        xhr.open('POST', httpurl, true);
        xhr.setRequestHeader("Content-Type","application/json;charset=UTF-8");
        xhr.timeout = timeout;
        xhr.ontimeout  = function (e) {
            errCallBack&&errCallBack('请求超时！');
            uiManager.showAlert('请求超时！');
        };
        xhr.onerror  = function () {
            errCallBack&&errCallBack('网络错误！');
            uiManager.showAlert('请求超时！');
        };
        xhr.send(JSON.stringify(data));
    };
}

